<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="03 函数-索引-事务-视图+触发器, luckyzmj 计算机 网络安全 渗透测试">
    <meta name="description" content="无">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google-site-verification" content="pBWoGvVEP36FzzS4xIpoMejc5UKi3RKcxd9rWWcjiDg" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>03 函数-索引-事务-视图+触发器 | Long</title>

    <link rel="icon" type="image/jpeg" href="https://s1.ax1x.com/2020/05/17/YR20js.jpg">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;900&display=swap" rel="stylesheet" media="print" onload="this.media='all'">
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="Long" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Long</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/census">
          
          <i class="fas fa-layer-group" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>统计</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-paper-plane" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>时轴</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tag" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-heartbeat" style="zoom: 0.6;"></i>
      
      <span>清单</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/List/music">
          
          <i class="fas fa-music" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>音乐</span>
        </a>
      </li>
      
      <li>
        <a href="/List/galleries">
          
          <i class="fas fa-image" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
      <li>
        <a href="/List/movies">
          
          <i class="fas fa-film" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>视频</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-envelope" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tools" class="waves-effect waves-light">
      
      <i class="fas fa-suitcase" style="zoom: 0.6;"></i>
      
      <span>百宝箱</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/Windows" class="waves-effect waves-light">
      
      <i class="fas fa-desktop" style="zoom: 0.6;"></i>
      
      <span>Windows</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-link" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://s1.ax1x.com/2020/05/17/YRWsYT.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Long</div>
        <div class="logo-desc">
            
            无
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-archive"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/census " style="margin-left:75px">
				  
				   <i class="fa fas fa-layer-group" style="position: absolute;left:50px" ></i>
			      
		          <span>统计</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-paper-plane" style="position: absolute;left:50px" ></i>
			      
		          <span>时轴</span>
                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tag" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-heartbeat"></i>
			
			清单
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/List/music " style="margin-left:75px">
				  
				   <i class="fa fas fa-music" style="position: absolute;left:50px" ></i>
			      
		          <span>音乐</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/galleries " style="margin-left:75px">
				  
				   <i class="fa fas fa-image" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
                <li>

                  <a href="/List/movies " style="margin-left:75px">
				  
				   <i class="fa fas fa-film" style="position: absolute;left:50px" ></i>
			      
		          <span>视频</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-envelope"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tools" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-suitcase"></i>
			
			百宝箱
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/Windows" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-desktop"></i>
			
			Windows
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-link"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/LuckyZmj/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/LuckyZmj/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/banner/8.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">03 函数-索引-事务-视图+触发器</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        background-color: white;
        width: 345px;
        padding-left: 20px;
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }
    
    #toc-content {
        height: calc(100vh - 300px);
        overflow: scroll;

    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
        bottom: 120px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                                <span class="chip bg-color">数据库</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                数据库
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-15
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-09-02
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    8.6k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    32 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="第一章-MySQL常用函数-理解"><a href="#第一章-MySQL常用函数-理解" class="headerlink" title="第一章 MySQL常用函数(理解)"></a>第一章 MySQL常用函数(理解)</h2><h3 id="1-1-字符串和数字函数"><a href="#1-1-字符串和数字函数" class="headerlink" title="1.1.字符串和数字函数"></a>1.1.字符串和数字函数</h3><h4 id="1-字符串函数"><a href="#1-字符串函数" class="headerlink" title="1)字符串函数"></a>1)字符串函数</h4><table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody><tr>
<td>CHAR_LENGTH(s)</td>
<td>返回字符串 s 的字符数</td>
<td>SELECT CHAR_LENGTH(‘itheima’) AS ‘长度’;</td>
</tr>
<tr>
<td><strong>CONCAT(s1,s2,…,sn)</strong></td>
<td>字符串 s1,s2 等多个字符串合并为一个字符串</td>
<td>SELECT CONCAT(‘I’,’love’,’you’);</td>
</tr>
<tr>
<td>LOWER(s)</td>
<td>将字符串 s 的所有字母变成小写字母</td>
<td>SELECT LOWER(‘ITHEIMA’);</td>
</tr>
<tr>
<td>UPPER(s)</td>
<td>将字符串转换为大写</td>
<td>SELECT UPPER(“itheima”);</td>
</tr>
<tr>
<td>SUBSTR(s,  start,length)</td>
<td>从字符串 s 的 start 位置(<strong>从1开始</strong>)截取长度为 length 的子字符串</td>
<td>SELECT SUBSTR(“itheima”,1,2);</td>
</tr>
<tr>
<td><strong>TRIM(s)</strong></td>
<td>去掉字符串 s 开始和结尾处的空格</td>
<td>SELECT TRIM(‘ itheima ‘)</td>
</tr>
</tbody></table>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 获取字符的长度</span>
<span class="token keyword">select</span> ename<span class="token punctuation">,</span>char_length<span class="token punctuation">(</span>ename<span class="token punctuation">)</span> <span class="token keyword">from</span> emp<span class="token punctuation">;</span>
<span class="token keyword">select</span> char_length<span class="token punctuation">(</span><span class="token string">'laofang'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 7</span>
<span class="token comment">-- 字符串拼接</span>
<span class="token keyword">select</span> concat<span class="token punctuation">(</span><span class="token string">'{ename:'</span><span class="token punctuation">,</span>ename<span class="token punctuation">,</span><span class="token string">',job:'</span><span class="token punctuation">,</span>job<span class="token punctuation">,</span><span class="token string">',sal:'</span><span class="token punctuation">,</span>sal<span class="token punctuation">,</span><span class="token string">'}'</span><span class="token punctuation">)</span> <span class="token keyword">from</span> emp<span class="token punctuation">;</span>
<span class="token comment">-- 转小写</span>
<span class="token keyword">select</span> lower<span class="token punctuation">(</span><span class="token string">'FangJiCai'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- fangjicai</span>
<span class="token comment">-- 转大写</span>
<span class="token keyword">select</span> upper<span class="token punctuation">(</span><span class="token string">'FangJiCai'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- FANGJICAI</span>
<span class="token comment">-- 截取字符串长度</span>
<span class="token keyword">select</span> substr<span class="token punctuation">(</span><span class="token string">'wubolin'</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- bo</span>
<span class="token comment">-- 去除字符串两边的空格</span>
<span class="token keyword">select</span> trim<span class="token punctuation">(</span><span class="token string">'    si qing  zhen   '</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- si qing  zhen</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="2-数字函数"><a href="#2-数字函数" class="headerlink" title="2)数字函数"></a>2)数字函数</h4><table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody><tr>
<td>RAND()</td>
<td>返回 0 到 1 的随机数</td>
<td>SELECT RAND();</td>
</tr>
<tr>
<td><strong>ROUND</strong>(小数 , 小数点后保留小数位数)</td>
<td>四舍五入保留几位小数</td>
<td>SELECT ROUND(3.1415926,2) ;</td>
</tr>
<tr>
<td>TRUNCATE(小数 , 小数点后保留小数位数)</td>
<td>不会四舍五入保留几位小数</td>
<td>SELECT  TRUNCATE(3.1415926,3);</td>
</tr>
<tr>
<td>LEAST(expr1, expr2, expr3, …)</td>
<td>返回列表中的最小值</td>
<td>SELECT LEAST(13, 14, 521, 74, 1)</td>
</tr>
<tr>
<td>GREATEST(expr1,  expr2,expr3, …)</td>
<td>返回列表中的最大值</td>
<td>SELECT GREATEST(13, 14, 521, 74, 1)</td>
</tr>
</tbody></table>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 获取0到1的随机数</span>
<span class="token keyword">select</span> rand<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">-- 四舍五入函数</span>
<span class="token keyword">select</span> <span class="token function">round</span><span class="token punctuation">(</span><span class="token number">3.1415926</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 3.142</span>
<span class="token comment">-- 数字截取,不做四舍五入</span>
<span class="token keyword">select</span> <span class="token keyword">truncate</span><span class="token punctuation">(</span><span class="token number">3.1415926</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 3.141</span>
<span class="token comment">-- 返回列表中的最小值</span>
<span class="token keyword">select</span> least<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span><span class="token number">40</span><span class="token punctuation">,</span><span class="token number">60</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 5</span>
<span class="token comment">-- 返回列表中的最大值</span>
<span class="token keyword">select</span> greatest<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span><span class="token number">40</span><span class="token punctuation">,</span><span class="token number">60</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 100</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h3 id="1-2-日期函数和高级函数"><a href="#1-2-日期函数和高级函数" class="headerlink" title="1.2 日期函数和高级函数"></a>1.2 日期函数和高级函数</h3><h4 id="1-日期函数"><a href="#1-日期函数" class="headerlink" title="1)日期函数"></a>1)日期函数</h4><table>
<thead>
<tr>
<th align="left">函数名</th>
<th align="left">描述</th>
<th align="left">实例</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong>NOW()</strong> 和 SYSDATE()</td>
<td align="left">返回系统的当前日期和时间</td>
<td align="left">SELECT NOW(); 或 SELECT SYSDATE();</td>
</tr>
<tr>
<td align="left">CURDATE()</td>
<td align="left">返回当前日期</td>
<td align="left">SELECT CURDATE();</td>
</tr>
<tr>
<td align="left">CURTIME()</td>
<td align="left">返回当前系统时间</td>
<td align="left">SELECT CURTIME();</td>
</tr>
<tr>
<td align="left"><strong>YEAR(d)</strong></td>
<td align="left"><strong>返回d的中的年份</strong></td>
<td align="left"><strong>SELECT YEAR(NOW());</strong></td>
</tr>
<tr>
<td align="left"><strong>MONTH(d)</strong></td>
<td align="left">返回d的中的月份</td>
<td align="left">SELECT MONTH(NOW());</td>
</tr>
<tr>
<td align="left"><strong>DAY(d)</strong></td>
<td align="left">返回d中的日</td>
<td align="left">SELECT DAY(NOW());</td>
</tr>
</tbody></table>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 返回系统的当前日期和时间</span>
<span class="token keyword">select</span> <span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 2020-12-11 09:26:29</span>
<span class="token keyword">select</span> sysdate<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 2020-12-11 09:26:29</span>
<span class="token comment">-- 返回当前日期</span>
<span class="token keyword">select</span> curdate<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 2020-12-11 </span>
<span class="token comment">-- 返回当前系统时间</span>
<span class="token keyword">select</span> curtime<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 09:27:08</span>
<span class="token comment">-- 返回年份</span>
<span class="token keyword">select</span> ename <span class="token keyword">from</span> emp <span class="token keyword">where</span> <span class="token keyword">year</span><span class="token punctuation">(</span>hiredate<span class="token punctuation">)</span><span class="token operator">=</span><span class="token string">'1980'</span><span class="token punctuation">;</span>
<span class="token keyword">select</span> <span class="token keyword">year</span><span class="token punctuation">(</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 2020</span>
<span class="token keyword">select</span> <span class="token keyword">year</span><span class="token punctuation">(</span><span class="token string">'2019-01-01'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">-- 2019</span>
<span class="token keyword">select</span> <span class="token keyword">year</span><span class="token punctuation">(</span><span class="token string">'2019/01/01'</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">-- 2019</span>
<span class="token comment">-- 返回月份</span>
<span class="token keyword">select</span> <span class="token keyword">month</span><span class="token punctuation">(</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 12</span>
<span class="token keyword">select</span> <span class="token keyword">month</span><span class="token punctuation">(</span><span class="token string">'2019/01/01'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 1</span>
<span class="token comment">-- 返回日</span>
<span class="token keyword">select</span> <span class="token keyword">day</span><span class="token punctuation">(</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 11</span>
<span class="token keyword">select</span> <span class="token keyword">day</span><span class="token punctuation">(</span><span class="token string">'2019-01-01'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- 1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="2-高级函数"><a href="#2-高级函数" class="headerlink" title="2)高级函数"></a>2)高级函数</h4><table>
<thead>
<tr>
<th align="left">函数名</th>
<th align="left">描述</th>
<th align="left">实例</th>
</tr>
</thead>
<tbody><tr>
<td align="left">CURRENT_USER()</td>
<td align="left">返回当前用户</td>
<td align="left">SELECT CURRENT_USER();</td>
</tr>
<tr>
<td align="left"><a target="_blank" rel="noopener" href="https://www.runoob.com/mysql/mysql-func-ifnull.html">IFNULL(v1,v2)</a></td>
<td align="left">如果 v1 的值不为 NULL，则返回 v1，否则返回 v2。</td>
<td align="left">SELECT IFNULL(null,’Hello Word’)</td>
</tr>
<tr>
<td align="left">ISNULL(expression)****</td>
<td align="left">判断表达式是否为 NULL,为空则为1,不为空则为0</td>
<td align="left">SELECT ISNULL(NULL);</td>
</tr>
</tbody></table>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 返回当前用户</span>
<span class="token keyword">select</span> <span class="token keyword">current_user</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- root@localhost</span>
<span class="token comment">-- ifnull(v1,v2)如果 v1 的值不为 NULL，则返回 v1，否则返回 v2</span>
<span class="token keyword">select</span> ename<span class="token punctuation">,</span>ifnull<span class="token punctuation">(</span>comm<span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">as</span> comm <span class="token keyword">from</span> emp<span class="token punctuation">;</span>

<span class="token comment">-- isnull判断表达式是否为 NULL,为空则为1,不为空则为0</span>
<span class="token keyword">select</span> isnull<span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- true 1</span>
<span class="token keyword">select</span> isnull<span class="token punctuation">(</span><span class="token number">666</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">-- false 0</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp <span class="token keyword">where</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp <span class="token keyword">where</span> <span class="token number">1</span><span class="token punctuation">;</span>
<span class="token comment">-- 查询comm为null的用户有哪些</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> emp <span class="token keyword">where</span> isnull<span class="token punctuation">(</span>comm<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h2 id="第二章-事务-掌握"><a href="#第二章-事务-掌握" class="headerlink" title="第二章 事务(掌握)"></a>第二章 事务(掌握)</h2><h3 id="2-1-事务介绍及操作"><a href="#2-1-事务介绍及操作" class="headerlink" title="2.1 事务介绍及操作"></a>2.1 事务介绍及操作</h3><h4 id="1-事务的概念"><a href="#1-事务的概念" class="headerlink" title="1)事务的概念"></a>1)事务的概念</h4><p>​      在实际的业务开发中，有些业务操作要多次访问数据库。<strong>一个业务要发送多条SQL语句给数据库执行。需要将多次访问数据库的操作视为一个整体来执行，要么所有的SQL语句全部执行成功。</strong>如果其中有一条SQL语句失败，就进行事务的回滚，所有的SQL语句全部执行失败。</p>
<p>简而言之，<strong>事务指的是逻辑上的一组操作,组成这组操作的各个单元要么全都成功,要么全都失败</strong>。</p>
<p> 事务作用：保证在一个事务中多次操作数据库表中数据时，要么全都成功,要么全都失败。</p>
<h4 id="2-事务的应用场景"><a href="#2-事务的应用场景" class="headerlink" title="2) 事务的应用场景"></a>2) 事务的应用场景</h4><p>​    1.转账业务:比如a给b转账,那么a扣款和b加款两部操作做要么都成功,要么都失败;</p>
<p>​    2.比如:学生管理系统中,要删除一个学生，那么需要删除学生的基本资料同时，也要删除和该学生相关的选课、成绩等信息;</p>
<h4 id="3-手动提交事务"><a href="#3-手动提交事务" class="headerlink" title="3)手动提交事务"></a>3)手动提交事务</h4><p>MYSQL中可以有两种方式进行事务的操作：</p>
<ol>
<li><p>手动提交事务：先开启，再提交</p>
</li>
<li><p>自动提交事务(<strong>默认的</strong>):即执行一条sql语句提交一次事务。</p>
<p>事务有关的SQL语句：</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>SQL语句</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>start transaction;</td>
<td>开启手动控制事务</td>
</tr>
<tr>
<td>commit;</td>
<td>提交事务</td>
</tr>
<tr>
<td>rollback;</td>
<td>回滚事务</td>
</tr>
</tbody></table>
<p>数据准备:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 创建账号表</span>
<span class="token keyword">create</span> <span class="token keyword">table</span> account<span class="token punctuation">(</span>
	id <span class="token keyword">int</span> <span class="token keyword">primary</span> <span class="token keyword">key</span> <span class="token keyword">auto_increment</span><span class="token punctuation">,</span>
	name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
	money <span class="token keyword">double</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment"># 初始化数据</span>
<span class="token keyword">insert</span> <span class="token keyword">into</span> account <span class="token keyword">values</span> <span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span><span class="token string">'a'</span><span class="token punctuation">,</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">insert</span> <span class="token keyword">into</span> account <span class="token keyword">values</span> <span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span><span class="token string">'b'</span><span class="token punctuation">,</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>说明:</p>
<p>需求1:a给b转账100元,演示提交事务和回滚事务</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 需求1:a给b转账100元,演示提交事务</span>
<span class="token comment">-- 1.1.手动开启事务</span>
<span class="token keyword">start</span> <span class="token keyword">transaction</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.2. a扣款100</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">-</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.3 b收款100</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">+</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'b'</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.4 事务提交</span>
<span class="token keyword">commit</span><span class="token punctuation">;</span>


<span class="token comment">-- 需求2:a给b转账100元,演示回滚事务</span>
<span class="token comment">-- 1.1.手动开启事务</span>
<span class="token keyword">start</span> <span class="token keyword">transaction</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.2. a扣款100</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">-</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.3 b收款100</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">+</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'b'</span><span class="token punctuation">;</span>
<span class="token comment">-- 1.4 事务回滚</span>
<span class="token keyword">rollback</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="4-自动提交事务"><a href="#4-自动提交事务" class="headerlink" title="4)自动提交事务"></a>4)自动提交事务</h4><p>  <strong>MySQL的每一条DML(增删改)语句都是一个单独的事务</strong>，每条语句都会自动开启一个事务，执行完毕自动提交事务，MySQL默认开始自动提交事务。</p>
<p>1.通过以下命令可以查看当前autocommit模式：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> variables <span class="token operator">like</span> <span class="token string">'%commit%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2.设置自动提交的参数为OFF:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">set</span> autocommit <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>  <span class="token comment">-- 0:OFF  1:ON</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>



<p>小结:</p>
<p>1.如何开启事务? </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>mysql默认事务自动开启<span class="token punctuation">,</span>在进行增删改时<span class="token punctuation">,</span>无需手动提交<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>通过<span class="token keyword">start</span> <span class="token keyword">transaction</span>可以手动开启事务<span class="token punctuation">,</span>那么这个开启的事务就需要手动提交<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>2.如何提交事务?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">commit</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>3.如何回滚事务?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">rollback</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h3 id="2-2-事务的回滚点和执行原理"><a href="#2-2-事务的回滚点和执行原理" class="headerlink" title="2.2 事务的回滚点和执行原理"></a>2.2 事务的回滚点和执行原理</h3><h4 id="1-回滚点介绍"><a href="#1-回滚点介绍" class="headerlink" title="1)回滚点介绍"></a>1)回滚点介绍</h4><p>上面的操作，如果回滚，直接回滚到事务开始前。有时我们只需要<strong>回滚到中间的某个位置</strong>，就可以设置回滚点。</p>
<p>语法:</p>
<table>
<thead>
<tr>
<th><strong>回滚点的操作语句</strong></th>
<th><strong>语句</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>设置回滚点</strong></td>
<td>savepoint 名字</td>
</tr>
<tr>
<td><strong>回到回滚点</strong></td>
<td>rollback to 名字</td>
</tr>
</tbody></table>
<p>练习:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1. 将数据还原到1000
2. 开启事务
3. 让a用户先减100块
4. 设置回滚点：savepoint itcast; 
5. 然后让a用户再次减100块
6. 回到回滚点：rollback to itcast
7. 最后commit提交事务<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 1.将数据还原到1000</span>
<span class="token comment">-- 2.开启事务</span>
<span class="token keyword">start</span> <span class="token keyword">transaction</span><span class="token punctuation">;</span>
<span class="token comment">-- 3. 让a用户先减100块</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">-</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">;</span>
<span class="token comment">-- 4. 设置回滚点：savepoint itcast; </span>
<span class="token keyword">savepoint</span> itcast<span class="token punctuation">;</span>
<span class="token comment">-- 5.然后让a用户再次减100块</span>
<span class="token keyword">update</span> account <span class="token keyword">set</span> money<span class="token operator">=</span>money<span class="token operator">-</span><span class="token number">100</span> <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">;</span>
<span class="token comment">-- 6. 回到回滚点：rollback to itcast</span>
<span class="token keyword">rollback</span> <span class="token keyword">to</span> itcast<span class="token punctuation">;</span>
<span class="token comment">-- 7. 最后commit提交事务</span>
<span class="token keyword">commit</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="2-事务原理"><a href="#2-事务原理" class="headerlink" title="2)事务原理"></a>2)事务原理</h4><p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002115077.png" alt="image-20210902002115077"></p>
<p>说明:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1)客户端连接mysql服务,服务端会对这个用户进行安全校验,通过后会创建一个临时的事务日志文件;
2)当用户直接向数据库插入数据时(因为mysql默认事务自动提交),数据会直接刷入数据库;
3)当用户调用start transaction命令手动开启事务时,事务相关的数据首先会写入这个临时的事务日志文件,然后当用户调用commit命令时,会将事务的数据刷入的数据库;
4)当用户进行事务的回滚时,会直接清空这个临时的事务日志文件(redo.log,undo.log,binlog);
5)当一个事务尚未提交,但是连接中断时,自动清除这个临时的事务文件;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>小结:</p>
<p>1.事务回滚点设置?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">savepoint</span> 回滚点名称<span class="token punctuation">;</span>
<span class="token comment">-- 回滚到指定回滚点</span>
<span class="token keyword">rollback</span> <span class="token keyword">to</span> 回滚点名称<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>2.事务原理?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>客户端连接mysql服务<span class="token punctuation">,</span>服务端会对这个用户进行安全校验<span class="token punctuation">,</span>通过后会创建一个临时的事务日志文件<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>当用户直接向数据库插入数据时<span class="token punctuation">(</span>因为mysql默认事务自动提交<span class="token punctuation">)</span><span class="token punctuation">,</span>数据会直接刷入数据库<span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>当用户调用<span class="token keyword">start</span> <span class="token keyword">transaction</span>命令手动开启事务时<span class="token punctuation">,</span>事务相关的数据首先会写入这个临时的事务日志文件<span class="token punctuation">,</span>然后当用户调用<span class="token keyword">commit</span>命令时<span class="token punctuation">,</span>会将事务的数据刷入的数据库<span class="token punctuation">;</span>
<span class="token number">4</span><span class="token punctuation">)</span>当用户进行事务的回滚时<span class="token punctuation">,</span>会直接清空这个临时的事务日志文件<span class="token punctuation">(</span>redo<span class="token punctuation">.</span>log<span class="token punctuation">,</span>undo<span class="token punctuation">.</span>log<span class="token punctuation">,</span>binlog<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">5</span><span class="token punctuation">)</span>当一个事务尚未提交<span class="token punctuation">,</span>但是连接中断时<span class="token punctuation">,</span>自动清除这个临时的事务文件<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h3 id="2-3-事务的四大特性-ACID-面试"><a href="#2-3-事务的四大特性-ACID-面试" class="headerlink" title="2.3 事务的四大特性(ACID)(面试)"></a>2.3 事务的四大特性(ACID)(面试)</h3><p>  数据库的事务必须具备<strong>ACID</strong>特性，ACID是指 Atomicity（原子性）、Consistensy（一致性）、Isolation（隔离性）和Durability（持久性）的英文缩写。</p>
<h4 id="1、隔离性（Isolation）"><a href="#1、隔离性（Isolation）" class="headerlink" title="1、隔离性（Isolation）"></a><strong>1、隔离性（Isolation）</strong></h4><p>​    <strong>多个用户并发的访问数据库时，一个用户的事务不能被其他用户的事务干扰，多个并发的事务之间要相互隔离。</strong></p>
<h4 id="2、持久性-Durability"><a href="#2、持久性-Durability" class="headerlink" title="2、持久性(Durability)"></a>2、持久性(Durability)</h4><p>​      <strong>指一个事务一旦被提交，它对数据库的改变将是永久性的，哪怕数据库发生异常，重启之后数据依然存在。</strong></p>
<h4 id="3、原子性-Atomicity"><a href="#3、原子性-Atomicity" class="headerlink" title="3、原子性(Atomicity)"></a><strong>3、原子性(Atomicity)</strong></h4><p><strong>原子性是指事务包装的一组sql(一组业务逻辑)是一个不可分割的工作单位</strong>，事务中的操作要么都发生，要么都不发生。</p>
<h4 id="4、一致性-Consistency"><a href="#4、一致性-Consistency" class="headerlink" title="4、一致性(Consistency)"></a><strong>4、一致性(Consistency)</strong></h4><p> <strong>一致性是指数据处于一种语义上有意义且正确的状态；</strong> </p>
<p>事务一致性是指事务执行的结果必须是使数据从一个一致性状态变到另一个一致性状态。</p>
<p>事务的成功与失败，最终数据库的数据都是符合实际生活的<strong>业务逻辑</strong>。一致性绝大多数<strong>依赖业务逻辑</strong>和原子性。</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002313241.png" alt="image-20210902002313241"></p>
<p>小结:</p>
<p>1.面试问题:说一下事务的4大特性?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>隔离性: 事务在并发下<span class="token punctuation">,</span>事务彼此隔离<span class="token punctuation">,</span>不受影响<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>原子性:事务是一个不可分割的整体<span class="token punctuation">,</span>要么都发生<span class="token punctuation">,</span>要么都不发生<span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>持久性:事务一旦提交<span class="token punctuation">,</span>对数据库数据的影响是永久性的<span class="token punctuation">,</span>那么数据库重启<span class="token punctuation">,</span>数据也不会丢失<span class="token punctuation">;</span>
<span class="token number">4</span><span class="token punctuation">)</span>一致性:首先一致性是基于原子性的<span class="token punctuation">,</span>强调的是一个业务逻辑的概念<span class="token punctuation">(</span>比如转账业务<span class="token punctuation">,</span>双方转账前总金额与转账后总金额要一致<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>2.事务相关的指令：</p>
<table>
<thead>
<tr>
<th>命令</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>start transaction;<br>begin;</td>
<td>手动开启事务</td>
</tr>
<tr>
<td>commit;</td>
<td>提交事务</td>
</tr>
<tr>
<td>rollback;</td>
<td>回滚事务</td>
</tr>
<tr>
<td>savepoint 回滚点名称;</td>
<td>设置事务回滚点</td>
</tr>
<tr>
<td>rollback to 回滚点名称;</td>
<td>回滚到回滚点</td>
</tr>
</tbody></table>
<hr style="height:10px;background-color:green;border:none;">

<h3 id="2-4-事务的并发访问引发的三个问题-面试"><a href="#2-4-事务的并发访问引发的三个问题-面试" class="headerlink" title="2.4 事务的并发访问引发的三个问题(面试)"></a>2.4 事务的并发访问引发的三个问题(面试)</h3><p>事务在操作时的理想状态：多个事务之间互不影响，如果隔离级别设置不当就可能引发并发访问问题。</p>
<table>
<thead>
<tr>
<th>并发访问的问题</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>脏读</td>
<td>一个事务读取到了另一个事务中<strong>尚未提交</strong>的数据。<strong>最严重，杜绝发生</strong>。</td>
</tr>
<tr>
<td>不可重复读</td>
<td>一个事务中多次读取的数据<strong>内容</strong>不一致，要求的是一个事务中多次读取时数据是不一致的，这是事务update时引发的问题</td>
</tr>
<tr>
<td>幻读（虚读）</td>
<td>一个事务内读取到了别的事务插入或者删除的数据，导致前后读取<strong>记录行数不同</strong>。这是insert或delete时引发的问题</td>
</tr>
</tbody></table>
<h4 id="1-脏读："><a href="#1-脏读：" class="headerlink" title="1.脏读："></a><strong>1.脏读：</strong></h4><p><strong>指一个事务读取了另外一个事务未提交的数据。(非常危险)</strong></p>
<p>说明:脏读强调一个事务读取了未提交的事务的数据;</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002430069.png" alt="image-20210902002430069"></p>
<h4 id="2-不可重复读："><a href="#2-不可重复读：" class="headerlink" title="2.不可重复读："></a><strong>2.不可重复读：</strong></h4><p><strong>在一个事务内多次读取表中的数据，多次读取的内容不同。</strong></p>
<p>​       说明:不可重复读就是一个事务读取了其他事务提交前后的数据,造成两次读取不一致的情况,多发生在事务<strong>update</strong>操作时;</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002456707.png" alt="image-20210902002456707"></p>
<p>说明：发生不可重复读的前提是1）事务多次读取<strong>相同条件</strong>下的数据2）另一个事务修改（<strong>update</strong>）完毕后事务进行了提交操作；</p>
<h4 id="3-幻读（虚读）"><a href="#3-幻读（虚读）" class="headerlink" title="3.幻读（虚读）"></a>3.幻读（虚读）</h4><p><strong>一个事务内读取到了别的事务插入或者删除的数据，导致前后读取记录行数不同</strong>,多发生在<strong>delete或insert</strong>时；</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002537169.png" alt="image-20210902002537169"></p>
<p>小结:</p>
<p>事务并发下的3个问题?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>脏读:一个事务读取了另一个事务未提交的数据<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>不可重复读:一个事务在相同条件下前后读取的内容不同<span class="token punctuation">(</span>强调:发生在其他事务进行<span class="token keyword">update</span>操作时<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>幻读<span class="token punctuation">(</span>虚读<span class="token punctuation">)</span>:一个事务在相同的条件下前后读取的行记录数不一致<span class="token punctuation">(</span>强调:其他事务发生<span class="token keyword">insert</span><span class="token punctuation">,</span>delte操作<span class="token punctuation">,</span>并且事务<span class="token keyword">commit</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h3 id="2-5-事务的隔离级别"><a href="#2-5-事务的隔离级别" class="headerlink" title="2.5 事务的隔离级别"></a>2.5 事务的隔离级别</h3><h4 id="1-介绍"><a href="#1-介绍" class="headerlink" title="1.介绍"></a>1.介绍</h4><p>MySQL数据库规范规定了4种隔离级别，用于解决上述出现的事务并发问题;</p>
<table>
<thead>
<tr>
<th>级别</th>
<th>名字</th>
<th>隔离级别</th>
<th>脏读</th>
<th>不可重复读</th>
<th>幻读</th>
<th>数据库默认隔离级别</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>读未提交</td>
<td>read uncommitted</td>
<td>是</td>
<td>是</td>
<td>是</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>读已提交</td>
<td>read committed</td>
<td>否</td>
<td>是</td>
<td>是</td>
<td>Oracle和SQL Server</td>
</tr>
<tr>
<td>3</td>
<td>可重复读</td>
<td>repeatable read</td>
<td>否</td>
<td>否</td>
<td>是</td>
<td>MySQL rr</td>
</tr>
<tr>
<td>4</td>
<td>串行化</td>
<td>serializable</td>
<td>否</td>
<td>否</td>
<td>否</td>
<td></td>
</tr>
</tbody></table>
<p>说明：其实三个问题，<strong>开发中最严重的问题就是脏读</strong>，这个问题一定要避免，而关于不可重复读和虚读其实只是感官上的错误，并不是<strong>逻辑上的错误</strong>。就是数据的<strong>时效性</strong>，所以这种问题并不属于很严重的错误。如果对于数据的时效性要求不是很高的情况下，我们是可以接受不可重复读和虚读的情况发生的。</p>
<h4 id="2、安全和性能对比"><a href="#2、安全和性能对比" class="headerlink" title="2、安全和性能对比"></a>2、安全和性能对比</h4><p>  安全:   串行化&gt;可重复读&gt;读已提交&gt;读未提交  </p>
<p>  性能:  串行化&lt;可重复读&lt;读已提交&lt;读未提交 </p>
<p>小结:</p>
<p>面试:数据库有哪些隔离级别?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1.</span>读未提交: 脏读<span class="token punctuation">,</span>不可重复读<span class="token punctuation">,</span>幻读
<span class="token number">2.</span>读已提交:不可重复读<span class="token punctuation">,</span>幻读
<span class="token number">3.</span>可重复读:幻读
<span class="token number">4.</span>串行化<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">



<p><strong>如何解决脏读的问题?</strong></p>
<p> 说明: 需要将全局的隔离级别进行提升(read committed),然后开启两个sqlyog窗口演示,演示完毕恢复隔离级别即可;</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1</span><span class="token punctuation">)</span>提高隔离级别 读已提交
<span class="token keyword">set</span> <span class="token keyword">global</span> <span class="token keyword">transaction</span> <span class="token keyword">isolation</span> <span class="token keyword">level</span> <span class="token keyword">read</span> <span class="token keyword">committed</span><span class="token punctuation">;</span>
<span class="token number">2</span>）刷新<span class="token keyword">session</span>（重新连接）<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<p>小结:</p>
<p>  1.查看全局事务隔离级别命令?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> @<span class="token variable">@tx_isolation</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>  2.设置全局隔离级别?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">set</span> <span class="token keyword">global</span> <span class="token keyword">transaction</span> <span class="token keyword">isolation</span> <span class="token keyword">level</span> 隔离界别名称<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>  3.如何解决脏读?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">提高事务隔离级别: <span class="token operator">&gt;=</span>读已提交<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h2 id="第三章-MySQL性能-理解"><a href="#第三章-MySQL性能-理解" class="headerlink" title="第三章 MySQL性能(理解)"></a>第三章 MySQL性能(理解)</h2><h3 id="3-1-分析-数据库查询效率低下"><a href="#3-1-分析-数据库查询效率低下" class="headerlink" title="3.1 分析-数据库查询效率低下"></a>3.1 分析-数据库查询效率低下</h3><p>要提高操作数据库的性能，有如下两种方式：</p>
<p>1.硬优化：就是软优化之后性能还很低，只能采取硬优化，最后的步骤了，就是公司花钱购买服务器。在硬件上进行优化。</p>
<p>2.<strong>软优化</strong>:  在操作和设计数据库方面上进行优化（重点）(<strong>表结构和sql语句</strong>)</p>
<h3 id="3-2-分析-执行次数比较多的语句"><a href="#3-2-分析-执行次数比较多的语句" class="headerlink" title="3.2 分析-执行次数比较多的语句"></a>3.2 分析-执行次数比较多的语句</h3><p>1.执行次数比较多的语句分类</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token operator">*</span> <span class="token number">1</span>）查询密集型

<span class="token operator">*</span> <span class="token number">2</span>）修改密集型  es solor<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>2.查询累计插入和返回数据条数，即查看<strong>当前数据库属于查询密集型还是修改密集型</strong>。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 查询累计插入和返回数据条数</span>
<span class="token keyword">show</span> <span class="token keyword">global</span> <span class="token keyword">status</span> <span class="token operator">like</span> <span class="token string">'Innodb_rows%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902002837634.png" alt="image-20210902002837634"></p>
<h2 id="第四章-索引-掌握"><a href="#第四章-索引-掌握" class="headerlink" title="第四章 索引(掌握)"></a>第四章 索引(掌握)</h2><h3 id="4-1-索引介绍及分类"><a href="#4-1-索引介绍及分类" class="headerlink" title="4.1 索引介绍及分类"></a>4.1 索引介绍及分类</h3><h4 id="1-什么是索引"><a href="#1-什么是索引" class="headerlink" title="1)什么是索引"></a>1)什么是索引</h4><p> Mysql官方对索引的定义为：<strong>索引（index）是帮助Mysql高效获取数据的数据结构。</strong></p>
<p><strong>可以得到索引的本质：索引就是数据结构：B+Tree</strong></p>
<h4 id="2-MySQL索引分类"><a href="#2-MySQL索引分类" class="headerlink" title="2)MySQL索引分类"></a>2)MySQL索引分类</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token operator">*</span> 主键（约束）索引
		主键约束<span class="token punctuation">(</span>唯一<span class="token operator">+</span>非空<span class="token punctuation">)</span><span class="token operator">+</span>提高查询效率
		
<span class="token operator">*</span> 唯一（约束）索引
		唯一约束<span class="token operator">+</span>提高查询效率

<span class="token operator">*</span> 普通索引
		仅提高查询效率

<span class="token operator">*</span> 组合（联合）索引
		多个字段组成索引
		<span class="token punctuation">[</span>联合主键索引
		联合唯一索引
		联合普通索引<span class="token punctuation">]</span>

<span class="token operator">*</span> 全文索引 <span class="token keyword">TEXT</span> BIGTEXY
		solr、es

<span class="token operator">*</span> <span class="token keyword">hash</span>索引
		根据<span class="token keyword">key</span><span class="token operator">-</span><span class="token keyword">value</span> 效率非常高
		 等值查询，不适合范围查询		<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h3 id="4-2-MySQL索引语法"><a href="#4-2-MySQL索引语法" class="headerlink" title="4.2 MySQL索引语法"></a>4.2 MySQL索引语法</h3><h4 id="4-2-1-索引创建"><a href="#4-2-1-索引创建" class="headerlink" title="4.2.1 索引创建"></a>4.2.1 索引创建</h4><h5 id="1-创建索引-【了解】"><a href="#1-创建索引-【了解】" class="headerlink" title="1) 创建索引 【了解】"></a>1) 创建索引 【了解】</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建普通索引</span>
<span class="token keyword">create</span> <span class="token keyword">index</span> 索引名 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">-- 创建唯一索引</span>
<span class="token keyword">create</span> <span class="token keyword">unique</span> <span class="token keyword">index</span> 索引名 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">-- 创建普通组合索引</span>
<span class="token keyword">create</span> <span class="token keyword">index</span> 索引名 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段<span class="token number">1</span><span class="token punctuation">,</span>字段<span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">-- 创建唯一组合索引</span>
<span class="token keyword">create</span> <span class="token keyword">unique</span> <span class="token keyword">index</span> 索引名 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段<span class="token number">1</span><span class="token punctuation">,</span>字段<span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>说明：</p>
<p>​    1.如果在同一张表中创建多个索引，要保证索引名是不能重复的</p>
<p>​    2.上述创建索引的方式比较麻烦，还需要指定索引名</p>
<p>​    <strong>3.采用上述方式不能添加主键索引</strong></p>
<p>【准备的创建表的SQL语句】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建学生表</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> student<span class="token punctuation">(</span>
 id <span class="token keyword">INT</span><span class="token punctuation">,</span>
 name <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 telephone <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>练习:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">-- 给name创建普通索引
create index idx_name on student(name);
-- 给telephone添加唯一索引
create unique index uniq_telephone on student(telephone);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-在已有表的字段上修改表时指定【了解】"><a href="#2-在已有表的字段上修改表时指定【了解】" class="headerlink" title="2) 在已有表的字段上修改表时指定【了解】"></a>2) 在已有表的字段上修改表时指定【了解】</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 添加一个主键，这意味着索引值必须是唯一的，且不能为NULL</span>
<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">primary</span> <span class="token keyword">key</span><span class="token punctuation">(</span>字段<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">--默认索引名：primary</span>

<span class="token comment">-- 添加唯一索引（除了NULL外，NULL可能会出现多次）</span>
<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">unique</span><span class="token punctuation">(</span>字段<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">-- 默认索引名：字段名</span>

<span class="token comment">-- 添加普通索引，索引值可以出现多次。</span>
<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">index</span><span class="token punctuation">(</span>字段<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">-- 默认索引名：字段名</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>【准备的创建表的SQL语句】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建学生表</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> student2<span class="token punctuation">(</span>
 id <span class="token keyword">INT</span><span class="token punctuation">,</span>
 name <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 telephone <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>练习:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">-- 给id添加主键索引
alter table student2 add primary key(id);
-- 给name字段添加普通索引 索引名称默认是字段名称
alter table student2 add index(name);
-- 给telephone添加唯一索引
alter table student2 add unique(telephone);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-创建表时指定【掌握】"><a href="#3-创建表时指定【掌握】" class="headerlink" title="3)  创建表时指定【掌握】"></a>3)  创建表时指定【掌握】</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建学生表</span>
<span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> student3<span class="token punctuation">(</span>
 id <span class="token keyword">INT</span> <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span> <span class="token comment">-- 主键索引</span>
 name <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 telephone <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token keyword">UNIQUE</span><span class="token punctuation">,</span> <span class="token comment">-- 唯一索引</span>
 sex <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
 birthday <span class="token keyword">DATE</span><span class="token punctuation">,</span>
 <span class="token keyword">INDEX</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span> <span class="token comment">-- 普通索引</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h4 id="4-2-2-查看与删除索引"><a href="#4-2-2-查看与删除索引" class="headerlink" title="4.2.2 查看与删除索引"></a>4.2.2 查看与删除索引</h4><h5 id="1-查看索引"><a href="#1-查看索引" class="headerlink" title="1) 查看索引"></a>1) 查看索引</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> <span class="token keyword">index</span> <span class="token keyword">from</span> 表名<span class="token punctuation">;</span> <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>练习:【查看student3表的索引信息】</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> <span class="token keyword">index</span> <span class="token keyword">from</span> student3<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="2-删除索引"><a href="#2-删除索引" class="headerlink" title="2) 删除索引"></a>2) 删除索引</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 两种方式</span>
<span class="token comment">-- 方式1:直接删除</span>
<span class="token keyword">drop</span> <span class="token keyword">index</span> 索引名 <span class="token keyword">on</span> 表名<span class="token punctuation">;</span>
<span class="token comment">-- 方式2:-- 修改表时删除</span>
<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">drop</span> <span class="token keyword">index</span> 索引名<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>练习:</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">练习1:删除student表的name普通索引
    drop index name_idx on student;
练习2:删除student表的telephone唯一索引
    alter table student drop index telephone_idx
练习3:删除主键
alter table student4 drop primary key;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>





<h3 id="4-4-索引优缺点及创建原则"><a href="#4-4-索引优缺点及创建原则" class="headerlink" title="4.4 索引优缺点及创建原则"></a>4.4 索引优缺点及创建原则</h3><h4 id="1-索引的优缺点"><a href="#1-索引的优缺点" class="headerlink" title="1.索引的优缺点"></a>1.索引的优缺点</h4><h5 id="1-优势"><a href="#1-优势" class="headerlink" title="1)优势"></a>1)优势</h5><p>​    1） 类似于书籍的目录索引，<strong>提高数据检索的效率，降低数据库的IO成本</strong>。<br>​    2） 索引底层就是排序，通过索引列对数据进行排序，降低数据排序的成本，<strong>降低CPU的消耗</strong>。</p>
<h5 id="2-劣势"><a href="#2-劣势" class="headerlink" title="2)劣势"></a>2)劣势</h5><ul>
<li>在数据库建立过程中，需花费较多的时间去建立并维护索引，特别是随着数据总量的增加，所花费的时间将不断递增(<strong>在海量数据前提下,创建索引成本高</strong>)。</li>
<li>在数据库中创建的索引需要占用一定的物理存储空间，这其中就包括数据表所占的数据空间以及所创建的每一个索引所占用的物理空间(<strong>会额外占用磁盘空间</strong>)。</li>
<li>在对表中的数据进行修改时，例如对其进行增加、删除或者是修改操作时，索引还需要进行动态的维护，这给数据库的维护速度带来了一定的麻烦(<strong>维护成本高</strong>)。</li>
</ul>
<h4 id="2-索引创建原则-面试"><a href="#2-索引创建原则-面试" class="headerlink" title="2.索引创建原则(面试)"></a>2.索引创建原则(面试)</h4><p>索引的设计可以遵循一些已有的原则，创建索引的时候请尽量考虑符合这些原则，便于提升索引的使用效率，更高效的使用索引。</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1.</span> 字段内容可识别度不能低于<span class="token number">70</span><span class="token operator">%</span>，字段内数据唯一值的个数不能低于<span class="token number">70</span><span class="token operator">%</span>
	例如：一个表数据只有<span class="token number">50</span>行，那么性别和年龄哪个字段适合创建索引，明显是年龄，因为年龄的唯一值个数比较多，性别只有两个选项。
	<span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">from</span> student3<span class="token punctuation">;</span><span class="token comment">-- 8</span>
    <span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token keyword">distinct</span> name<span class="token punctuation">)</span> <span class="token keyword">from</span> student3<span class="token punctuation">;</span>
    <span class="token keyword">select</span> <span class="token punctuation">(</span><span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token keyword">distinct</span> name<span class="token punctuation">)</span> <span class="token keyword">from</span> student3<span class="token punctuation">)</span><span class="token operator">/</span><span class="token punctuation">(</span><span class="token keyword">select</span> <span class="token function">count</span><span class="token punctuation">(</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token keyword">from</span> student3<span class="token punctuation">)</span>

<span class="token number">2.</span> 经常使用<span class="token keyword">where</span>条件搜索的字段，例如<span class="token keyword">user</span>表的id name等字段。

<span class="token number">3.</span> 经常使用表连接的字段（内连接、外连接），可以加快连接的速度。

<span class="token number">4.</span> 经常排序的字段 <span class="token keyword">order</span> <span class="token keyword">by</span>，因为索引已经是排过序的，这样一来可以利用索引的排序，加快排序查 询速度。

<span class="token number">5.</span>空间原则（字段占用空间越小也好）

<span class="token operator">*</span> 注意: 索引并不是越多越好<span class="token punctuation">,</span>因为索引的建立和维护都是需要耗时的 创建表时需要通过数据库去维护索引，添加记录、更新、修改时，也需要更新索引，会间接影响数据库的效率。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h3 id="4-5-索引的数据结构【了解】"><a href="#4-5-索引的数据结构【了解】" class="headerlink" title="4.5 索引的数据结构【了解】"></a>4.5 索引的数据结构【了解】</h3><h4 id="4-5-1-索引示例介绍"><a href="#4-5-1-索引示例介绍" class="headerlink" title="4.5.1 索引示例介绍"></a>4.5.1 索引示例介绍</h4><p>我们知道<strong>索引</strong>是帮助MySQL高效获取数据的一种<strong>排好序</strong>的<strong>数据结构</strong>。</p>
<p>以磁盘顺序迭代查询与二叉树查找为例:</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902003738571.png" alt="image-20210902003738571"></p>
<p>如果没有使用索引查询数据，比如查询col1=6,需要经过6次io；</p>
<p>   如何减少磁盘io次数？</p>
<p>  如果读取col2=89,那么需要2次io；</p>
<hr style="height:10px;background-color:green;border:none;">

<h4 id="4-5-2-二叉查找树和红黑树"><a href="#4-5-2-二叉查找树和红黑树" class="headerlink" title="4.5.2 二叉查找树和红黑树"></a>4.5.2 二叉查找树和红黑树</h4><p><strong>数据结构学习网站(美国旧金山大学)</strong></p>
<pre class="line-numbers language-http" data-language="http"><code class="language-http"><span class="token header-name keyword">https:</span>//www.cs.usfca.edu/~galles/visualization/Algorithms.html<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="1-二叉查找树"><a href="#1-二叉查找树" class="headerlink" title="1.二叉查找树"></a>1.二叉查找树</h5><p>左边的子节点比父节点小，右边的子节点比父节点大;</p>
<p><img src="https://i.loli.net/2021/09/02/SzmLxUCbOfIAD3Y.png" alt="image-20210902100458124"></p>
<h5 id="2-红黑树"><a href="#2-红黑树" class="headerlink" title="2.红黑树"></a>2.红黑树</h5><p>平衡二叉树（左旋、右旋、变色）;</p>
<p>说明:存储千万数据,树高大约<strong>为23</strong>;</p>
<p><img src="https://i.loli.net/2021/09/02/Ucb8waV4jdoiuD9.png" alt="image-20210902100545976"></p>
<p><strong>树的高度越高,那么部分数据查询要经过的io的次数就会越多;</strong></p>
<hr style="height:10px;background-color:green;border:none;">

<h4 id="4-5-3-BTree"><a href="#4-5-3-BTree" class="headerlink" title="4.5.3.BTree"></a>4.5.3.BTree</h4><p>从结构树看,<strong>树的高度就是查询数据时的最多IO次数</strong>,那么如何将树的高度压低？</p>
<pre><code>      将每个节点存储的数据尽量多一些</code></pre>
<p>多路平衡搜索树;</p>
<p>说明:数据库一个节点<strong>16KB,**每个节点的元素由索引(8字节),指针域(6个字节),数据组成（比如1kb）,存储千万数据树</strong>高接近6;**</p>
<p>一个节点存储的元素个数:16*1024/(8+6+1024)约等于15</p>
<p>   如果存储的数据占1kb，那么每个节点存储的元素个数是<strong>15个元素</strong>，那么如果存储1000w数据树高多少？<strong>6</strong></p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902003842317.png" alt="image-20210902003842317"></p>
<p>思考：如何进一步降低树的高度及优化查询？</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1）数据查询的过程中，有一些数据data的加载时没有意义且浪费磁盘io；
2）如果要进行范围查询，那么需要反复从根节点读取数据；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<hr style="height:10px;background-color:green;border:none;">

<h4 id="4-5-4-B-Tree"><a href="#4-5-4-B-Tree" class="headerlink" title="4.5.4 B+Tree"></a>4.5.4 B+Tree</h4><h5 id="1-结构介绍"><a href="#1-结构介绍" class="headerlink" title="1.结构介绍"></a>1.结构介绍</h5><p>1）B+tree将树分为叶子节点和非叶子节点，其中非叶子节点只存储索引+指针，不存储数据，而叶子节点存储索引+指针域+数据；</p>
<p>   如果一个B+tree的树高时3的话，那么非叶子节点2层，叶子节点1层；</p>
<p>非叶子节点:16*1024/(8+6)=1170</p>
<p>​    非叶子节点两层：1170个元素，如果是两层，那么元素数量：1170*1170=<strong>1,368,900</strong></p>
<p>​    叶子节点：因为包含索引+指针域+数据  —–16*1.24/(8+6+1025)=15</p>
<p>   总共：1,368,900*15=20,533,500</p>
<p>优化BTree（非叶子节点：索引+指针、叶子节点：索引+数据【地址】）;</p>
<p><img src="https://gitee.com/ergou15154/drawing-bed/raw/master/source/image-20210902003911405.png" alt="image-20210902003911405"></p>
<p>说明：b+tree通过<strong>非叶子节点不存储数据</strong>，进一步降低了树的高度；</p>
<p>​           通过叶子节点之间维护了指针双向指向，<strong>提高了区间的访问能力；</strong></p>
<p>存储2千w数据,树高维护在3左右!</p>
<p><strong>小结：</strong></p>
<p>B+Tree好处：</p>
<p>​    1）(非叶子节点只存储索引和指针域,不保存数据)降低树的高度,意味着数据查询的io次数减少;</p>
<p>​    2)   叶子节点按照索引排好序，支持范围查找，速度会很快。</p>
<p>​    3）还有一点是mysql将根节点都加载到内存中，每张表有一个根节点，<strong>大小是16KB</strong>.那么这样的好处，按照上述如果是千万条数据，那么只有2次磁盘IO.这就是为什么我们加完索引之后瞬间查到数据的原因了。</p>
<p>最终结论：</p>
<p>   <strong>通过将树的每个节点存储的元素增大来降低树的高度；</strong></p>
<h5 id="2-MySQL中的B-Tree"><a href="#2-MySQL中的B-Tree" class="headerlink" title="2. MySQL中的B+Tree"></a>2. MySQL中的B+Tree</h5><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 查看mysql索引节点大小</span>
<span class="token keyword">show</span> <span class="token keyword">global</span> <span class="token keyword">status</span> <span class="token operator">like</span> <span class="token string">'innodb_page_size'</span><span class="token punctuation">;</span> <span class="token comment">-- 16kb</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>MySql索引数据结构对经典的B+Tree进行了优化。在原B+Tree的基础上，增加一个指向相邻叶子节点的链表指针，就形成了带有顺序指针的B+Tree，<strong>提高区间访问的性能</strong>。</p>
<hr style="height:10px;background-color:green;border:none;">

<h2 id="第五章-视图-掌握"><a href="#第五章-视图-掌握" class="headerlink" title="第五章 视图(掌握)"></a>第五章 视图(掌握)</h2><h3 id="5-1-视图应用与创建"><a href="#5-1-视图应用与创建" class="headerlink" title="5.1 视图应用与创建"></a>5.1 视图应用与创建</h3><h4 id="1-概述"><a href="#1-概述" class="headerlink" title="1.概述"></a>1.概述</h4><p>​    1.视图（View）是一种虚拟存在的表，行和列的数据来源于定义视图的查询中使用的表，并且是在使用视图时动态生成的。</p>
<p>​     2.视图和普通表一样使用，但是视图并不存储数据。<strong>通俗的讲，视图就是一条SELECT语句执行后返回的结果集。</strong></p>
<h4 id="2-应用场景"><a href="#2-应用场景" class="headerlink" title="2.应用场景"></a>2.应用场景</h4><p>1）多个地方用到同样的查询结果</p>
<p>2）该查询结果使用的sql语句较复杂</p>
<p>创建视图语法格式:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">view</span> 视图名
<span class="token keyword">as</span>
查询语句<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>需求:查看所有国家和对应城市的信息</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 视图是一张虚拟的表,除了不保存数据数据外,其他规则都改表table一致</span>
<span class="token keyword">create</span> <span class="token keyword">view</span> country_city_view <span class="token keyword">as</span> 
<span class="token keyword">select</span> city<span class="token punctuation">.</span><span class="token operator">*</span><span class="token punctuation">,</span>country<span class="token punctuation">.</span>country_name 
<span class="token keyword">from</span> country<span class="token punctuation">,</span>city <span class="token keyword">where</span> country<span class="token punctuation">.</span>country_id<span class="token operator">=</span>city<span class="token punctuation">.</span>country_id<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>



<h4 id="3-视图和表的区别"><a href="#3-视图和表的区别" class="headerlink" title="3.视图和表的区别"></a>3.视图和表的区别</h4><pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown">	 使用方式	  占用物理空间

视图	完全相同	 视图中的数据不保存，仅仅保存的是sql逻辑，磁盘上只有表结构，没有数据

表	 完全相同	  占用<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="4-视图的好处"><a href="#4-视图的好处" class="headerlink" title="4.视图的好处"></a>4.视图的好处</h4><pre class="line-numbers language-markdown" data-language="markdown"><code class="language-markdown"><span class="token list punctuation">*</span> 1、提高sql语句重用性，效率高(避免sql语句多次编译)
<span class="token list punctuation">*</span> 2、和表实现了分离，提高了安全性，使用视图的用户只能访问他们被允许查询的结果集<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h3 id="5-2-视图修改-查看与删除"><a href="#5-2-视图修改-查看与删除" class="headerlink" title="5.2 视图修改,查看与删除"></a>5.2 视图修改,查看与删除</h3><h4 id="1-视图修改"><a href="#1-视图修改" class="headerlink" title="1)视图修改"></a>1)视图修改</h4><p>方式1-创建过程覆盖旧的视图,达到修改的操作</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token operator">or</span> <span class="token keyword">replace</span> <span class="token keyword">view</span> 视图名
<span class="token keyword">as</span>
查询语句<span class="token punctuation">;</span>
<span class="token comment">-- 说明：如果存在该视图名就是修改视图，如果不存在该视图名则创建视图。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>需求：修改上述视图city_country_view，select语句变为查询城市名是上海的城市信息和所属国家信息</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token operator">or</span> <span class="token keyword">replace</span> <span class="token keyword">view</span> country_city_view <span class="token keyword">as</span>
<span class="token keyword">select</span>
city<span class="token punctuation">.</span><span class="token operator">*</span><span class="token punctuation">,</span>country<span class="token punctuation">.</span>country_name 
<span class="token keyword">from</span> country<span class="token punctuation">,</span>city <span class="token keyword">where</span> country<span class="token punctuation">.</span>country_id<span class="token operator">=</span>city<span class="token punctuation">.</span>country_id <span class="token operator">and</span> city<span class="token punctuation">.</span>city_name<span class="token operator">=</span><span class="token string">'上海'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>方式2:使用alter修改</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">alter</span> <span class="token keyword">view</span> 视图名
<span class="token keyword">as</span>
查询语句<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>需求：修改上述视图city_country_view，select语句变为查询城市名是北京的城市信息和所属国家信息</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">alter</span> <span class="token keyword">view</span> country_city_view <span class="token keyword">as</span>
<span class="token keyword">select</span>
city<span class="token punctuation">.</span><span class="token operator">*</span><span class="token punctuation">,</span>country<span class="token punctuation">.</span>country_name 
<span class="token keyword">from</span> country<span class="token punctuation">,</span>city <span class="token keyword">where</span> country<span class="token punctuation">.</span>country_id<span class="token operator">=</span>city<span class="token punctuation">.</span>country_id <span class="token operator">and</span> city<span class="token punctuation">.</span>city_name<span class="token operator">=</span><span class="token string">'北京'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-查看视图"><a href="#2-查看视图" class="headerlink" title="2)查看视图"></a>2)查看视图</h4><p>查看视图指令与table指令格式一致.</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">show</span> <span class="token keyword">tables</span><span class="token punctuation">;</span>
<span class="token keyword">desc</span> country_view<span class="token punctuation">;</span>
<span class="token keyword">show</span> <span class="token keyword">create</span> <span class="token keyword">table</span> country_view<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h4 id="3-删除视图"><a href="#3-删除视图" class="headerlink" title="3)删除视图"></a>3)删除视图</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">drop</span> <span class="token keyword">view</span> 视图名<span class="token punctuation">,</span>视图名<span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>需求:删除 country_view视图</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">drop</span> <span class="token keyword">view</span> country_view<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>小结:</p>
<p>视图应用场景及好处?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">场景:
<span class="token number">1</span><span class="token punctuation">)</span>多场景使用相同且非常复杂的查询<span class="token keyword">sql</span><span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>在一些数据敏感<span class="token punctuation">,</span>涉及到安全的场景<span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>网络访问密集的场景<span class="token punctuation">(</span>减少网络io开销<span class="token punctuation">)</span>；
好处:
<span class="token number">1</span><span class="token punctuation">)</span>提高<span class="token keyword">sql</span>的复用性<span class="token punctuation">;</span>
<span class="token number">2</span><span class="token punctuation">)</span>提高数据的安全性和数据库性能<span class="token punctuation">;</span>
<span class="token number">3</span><span class="token punctuation">)</span>减少网络io开销<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>创建语句格式?</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">view</span> 视图名称 <span class="token keyword">as</span>  <span class="token keyword">select</span>语句<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>



<hr style="height:10px;background-color:green;border:none;">

<h2 id="第六章-触发器-了解"><a href="#第六章-触发器-了解" class="headerlink" title="第六章 触发器(了解)"></a>第六章 触发器(了解)</h2><h3 id="6-1触发器概述与创建"><a href="#6-1触发器概述与创建" class="headerlink" title="6.1触发器概述与创建"></a>6.1触发器概述与创建</h3><h4 id="1-触发器概述"><a href="#1-触发器概述" class="headerlink" title="1)触发器概述"></a>1)触发器概述</h4><p>​    1.触发器主要是通过<strong>事件进行触发而被执行</strong>的,我们可以在修改数据的前后绑定事件,触发执行定义的SQL;</p>
<p>​    2.触发器是与表有关的数据库对象，指在 <strong>insert/update/delete</strong> 之前或之后，触发并执行触发器中定义的SQL语句集合。</p>
<p>​    3.使用<strong>别名 OLD 和 NEW 来引用触发器中发生变化的记录内容</strong>，这与其他的数据库是相似的。</p>
<p>说明：OLD表示操作前的对象，NEW 表示操作之后的对象。</p>
<table>
<thead>
<tr>
<th>触发器类型</th>
<th>NEW 和 OLD的使用</th>
</tr>
</thead>
<tbody><tr>
<td>INSERT 型触发器</td>
<td><strong>NEW 表示将要或者已经新增的数据</strong>，插入之前没有数据，所以不能使用OLD</td>
</tr>
<tr>
<td>UPDATE 型触发器</td>
<td><strong>OLD 表示修改之前的数据 , NEW 表示将要或已经修改后的数据</strong></td>
</tr>
<tr>
<td>DELETE 型触发器</td>
<td><strong>OLD 表示将要或者已经删除的数据</strong>,删除之后没有数据了，所以不能使用NEW</td>
</tr>
</tbody></table>
<h4 id="2-创建触发器"><a href="#2-创建触发器" class="headerlink" title="2)创建触发器"></a>2)创建触发器</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 语法</span>
<span class="token keyword">create</span> <span class="token keyword">trigger</span> trigger_name
before<span class="token operator">/</span><span class="token keyword">after</span> <span class="token keyword">insert</span><span class="token operator">/</span><span class="token keyword">update</span><span class="token operator">/</span><span class="token keyword">delete</span>
<span class="token keyword">on</span> tbl_name
<span class="token keyword">for each row</span>   <span class="token comment">-- 行级触发器</span>
	trigger_stmt <span class="token punctuation">;</span>
说明：
	<span class="token number">1</span>）before<span class="token operator">/</span><span class="token keyword">after</span>位置称为触发时机，一个触发器只能选择一个
	<span class="token number">2</span>）<span class="token keyword">insert</span><span class="token operator">/</span><span class="token keyword">update</span><span class="token operator">/</span><span class="token keyword">delete</span>位置称为触发事件，一个触发器只能选择一个
	<span class="token number">3</span>）<span class="token keyword">for each row</span>称为行级触发器，触发器绑定实质是表中的所有行，因此当每一行发生指定改变的时候，就会触发触发器。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>数据准备:</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">-- 创建员工表，员工信息</span>
<span class="token keyword">create</span> <span class="token keyword">table</span> emp<span class="token punctuation">(</span>
	id <span class="token keyword">int</span> <span class="token keyword">primary</span> <span class="token keyword">key</span> <span class="token keyword">auto_increment</span><span class="token punctuation">,</span>
    name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span> <span class="token operator">not</span> <span class="token boolean">null</span><span class="token punctuation">,</span>
    age <span class="token keyword">int</span><span class="token punctuation">,</span>
    salary <span class="token keyword">int</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">insert</span> <span class="token keyword">into</span> emp<span class="token punctuation">(</span>id<span class="token punctuation">,</span>name<span class="token punctuation">,</span>age<span class="token punctuation">,</span>salary<span class="token punctuation">)</span> <span class="token keyword">values</span><span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span> <span class="token string">'金毛狮王'</span><span class="token punctuation">,</span><span class="token number">40</span><span class="token punctuation">,</span><span class="token number">2500</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">insert</span> <span class="token keyword">into</span> emp<span class="token punctuation">(</span>id<span class="token punctuation">,</span>name<span class="token punctuation">,</span>age<span class="token punctuation">,</span>salary<span class="token punctuation">)</span> <span class="token keyword">values</span><span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span> <span class="token string">'蝙蝠王'</span><span class="token punctuation">,</span><span class="token number">38</span><span class="token punctuation">,</span><span class="token number">3100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">-- 创建一张日志表,存放日志信息</span>
<span class="token keyword">create</span> <span class="token keyword">table</span> emp_logs<span class="token punctuation">(</span>
    id <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token keyword">primary</span> <span class="token keyword">key</span> <span class="token keyword">auto_increment</span><span class="token punctuation">,</span>
    operation <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token operator">not</span> <span class="token boolean">null</span> <span class="token keyword">comment</span> <span class="token string">'操作类型, insert/update/delete'</span><span class="token punctuation">,</span>
    operate_time <span class="token keyword">datetime</span> <span class="token operator">not</span> <span class="token boolean">null</span> <span class="token keyword">comment</span> <span class="token string">'操作时间'</span><span class="token punctuation">,</span>
    operate_id <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token operator">not</span> <span class="token boolean">null</span> <span class="token keyword">comment</span> <span class="token string">'操作表的ID,emp表数据的id'</span><span class="token punctuation">,</span>
    operate_params <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">500</span><span class="token punctuation">)</span> <span class="token keyword">comment</span> <span class="token string">'操作参数,插入emp中的数据'</span>
<span class="token punctuation">)</span><span class="token keyword">engine</span><span class="token operator">=</span><span class="token keyword">innodb</span> <span class="token keyword">default</span> <span class="token keyword">charset</span><span class="token operator">=</span>utf8<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p> <strong>需求1:创建 insert 型触发器，完成插入数据时的日志记录  new</strong></p>
<p>需求2:创建 update 型触发器，完成更新数据时的日志记录</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">create</span> <span class="token keyword">trigger</span> update_tri 
<span class="token keyword">after</span> <span class="token keyword">update</span>
<span class="token keyword">on</span> emp
<span class="token keyword">for each row</span>
<span class="token keyword">insert</span> <span class="token keyword">into</span> emp_logs <span class="token keyword">values</span><span class="token punctuation">(</span><span class="token boolean">null</span><span class="token punctuation">,</span><span class="token string">'update'</span><span class="token punctuation">,</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>old<span class="token punctuation">.</span>id<span class="token punctuation">,</span>concat<span class="token punctuation">(</span><span class="token string">'操作之前数据:'</span><span class="token punctuation">,</span>old<span class="token punctuation">.</span>id<span class="token punctuation">,</span>old<span class="token punctuation">.</span>name<span class="token punctuation">,</span>old<span class="token punctuation">.</span>age<span class="token punctuation">,</span>old<span class="token punctuation">.</span>salary<span class="token punctuation">,</span><span class="token string">'操作之后数据:'</span><span class="token punctuation">,</span>new<span class="token punctuation">.</span>id<span class="token punctuation">,</span>new<span class="token punctuation">.</span>name<span class="token punctuation">,</span>new<span class="token punctuation">.</span>age<span class="token punctuation">,</span>new<span class="token punctuation">.</span>salary<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>需求3:创建delete 行的触发器 , 完成删除数据时的日志记录  old</strong></p>
<hr style="height:10px;background-color:green;border:none;">

<h3 id="6-2-触发器查看与删除"><a href="#6-2-触发器查看与删除" class="headerlink" title="6.2 触发器查看与删除"></a>6.2 触发器查看与删除</h3><h4 id="1-查看触发器"><a href="#1-查看触发器" class="headerlink" title="1)查看触发器"></a>1)查看触发器</h4><p>可使用指令或者可视化工具查看触发器;</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SHOW</span> TRIGGERS<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h4 id="2-删除触发器"><a href="#2-删除触发器" class="headerlink" title="2) 删除触发器"></a>2) 删除触发器</h4><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">drop</span> <span class="token keyword">trigger</span> trigger_name <span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>





<h2 id="索引总结"><a href="#索引总结" class="headerlink" title="索引总结"></a>索引总结</h2><p>1.1 索引的创建</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 方式1：</span>
	<span class="token comment"># 普通索引</span>
	<span class="token keyword">create</span> <span class="token keyword">index</span> 索引名称 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段名称<span class="token punctuation">,</span>字段名称<span class="token number">2</span>，<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment"># 创建唯一索引</span>
	<span class="token keyword">create</span> <span class="token keyword">unique</span> <span class="token keyword">index</span> 索引名称 <span class="token keyword">on</span> 表名<span class="token punctuation">(</span>字段名称<span class="token punctuation">,</span>字段名称<span class="token number">2</span>，<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment"># 方式2：</span>
	<span class="token comment"># 普通索引</span>
	<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">index</span><span class="token punctuation">(</span>字段名称<span class="token punctuation">,</span>字段名称<span class="token number">2</span><span class="token punctuation">,</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment"># 唯一索引</span>
	<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">unique</span><span class="token punctuation">(</span>字段名称，字段名称<span class="token number">2</span>，<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment"># 主键索引</span>
	<span class="token keyword">alter</span> <span class="token keyword">table</span> 表名 <span class="token keyword">add</span> <span class="token keyword">primary</span> <span class="token keyword">key</span><span class="token punctuation">(</span>字段<span class="token number">1</span>，字段<span class="token number">2</span>，<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment"># 方式3：掌握</span>
	<span class="token keyword">create</span> <span class="token keyword">table</span> 表名<span class="token punctuation">(</span>
    	id <span class="token keyword">int</span> <span class="token keyword">primary</span> <span class="token keyword">key</span> <span class="token keyword">auto_increment</span><span class="token punctuation">,</span><span class="token comment">-- 主键且自增</span>
        name <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        tele <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">)</span> <span class="token keyword">unique</span><span class="token punctuation">,</span>
        <span class="token keyword">index</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>1.2 索引分类</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">主键索引：特点 唯一<span class="token operator">+</span> 非空<span class="token operator">+</span> 提高查询效率 底层维护的是主键索引<span class="token punctuation">(</span>聚集索引，通过索引数据，就可以找到满足条件的任意数据<span class="token comment">--叶子节点数据都包含)</span>
唯一索引： 特点 唯一 <span class="token operator">+</span> 提交查询效率   底层维护了唯一索引<span class="token punctuation">(</span>非聚集索引，查询过程是先通过唯一索引<span class="token keyword">btree</span>检索到叶子节点下保存的主键值，然后再取主键索引根据主键的值查询对应的数据<span class="token comment">--回表查询)</span>
唯一索引： 特点：没有任何约束，仅仅提高查询效率，底层与唯一索引类似；
<span class="token keyword">Hash</span>索引：特点： 非常适合等值查询，但是不适合范围查询；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>回表查询示意图：</p>
<p><img src="https://i.loli.net/2021/09/02/kMwcOiXrY1qQ4vG.png" alt="image-20210819084509775"></p>
<p>说明：实际情况中，普通索引或者唯一索引是btree结构(不是上图中的二叉树)；</p>
<p>面试题：</p>
<p>1.什么是回表查询？</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">一般主键查询时，不会回表查询，但是对应查询如果走非主键索引，那么需要先走普通索引拿主键索引值，然后再去主键索引查询拿数据；<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2.如何避免回表查询？</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">因为回表查询，整体效率是慢了一些；
 避免方式：
 	1.尽量让查询走主键索引；
 	2.建立联合索引；
 		举例： 根据手机号查询姓名；
 	    在表中将手机号和姓名一起创建一个【联合索引】，这样就可以直接在索引树中拿数据，避免了回表查询；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>3.创建索引的原则</p>
<pre class="line-numbers language-tex" data-language="tex"><code class="language-tex">1.创建索引的表示度要高
	如何统计表示度？
	select count(distinct 索引字段)/count(索引字段) from 表名；
	结果越接近1越理想；
2.条件中要使用对应的表的字段
	2.1 where条件中【经常】使用的字段（having查询不走索引）；
	2.2 多表join联查时，on关键字后边的字段；
3.在排序的场景 order by 字段；
4.空间原则
	主键字段在满足业务需求的情况下，占空间越小越好；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>4.索引失效的原因？</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token number">1.</span>索引字段使用函数
	<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span>  表名 <span class="token keyword">where</span> trim<span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token operator">=</span><span class="token string">'xxxx'</span>；
<span class="token number">2.</span>索引字段参与数学运算
	<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> 表名 <span class="token keyword">where</span> id<span class="token operator">+</span><span class="token number">100</span><span class="token operator">=</span><span class="token number">200</span><span class="token punctuation">;</span>
<span class="token number">3.</span>索引字段存在类型转换
	<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> 表名 <span class="token keyword">where</span> name<span class="token operator">=</span><span class="token number">500</span><span class="token punctuation">;</span>
<span class="token number">4</span>索引字段频繁的进行写操作，导致索引树拼接的维护构建；	
	如果一个字段拼接修改，那么完全没必有在这个字段创建索引了；<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Long</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://ergou15154.gitee.io/posts/a1e44ab1.html">https://ergou15154.gitee.io/posts/a1e44ab1.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Long</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                                    <span class="chip bg-color">数据库</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,twitter,facebook,google,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/null" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/null" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    .v[data-class="v"] .vwrap .vheader .vinput {
      width: 32%;
      border-bottom: 1px dashed #dedede;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
let metaPlaceholder = {"nick":"昵称/QQ号(必填)","mail":"邮箱(必填)","link":"网址(https://)"} ;
//这里要换行
new Valine({
        el: '#vcomments',
        appId: 'Ucrxxxxxxxxxxxxxxxx-xxxxsz',
        appKey: 'zPsLxxxxxxxxxxxxxxerLmd',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'monsterid',
        pageSize: '10',
        lang: 'zh-CN',
        placeholder: '留下你的足迹..',
        meta: ["nick", "mail", "link"],
        recordIP: 'true' === 'true',
        enableQQ: 'monsterid',
        requiredFields: ["d142de78a3402022b268b12dab90d819"],
        master: ["d142de78a3402022b268b12dab90d819"],
        friends: ["cb3e577ff029d6073400d5557effd41f", ""],
        tagMeta: ["博主", "小伙伴", "访客"],
        metaPlaceholder: metaPlaceholder,

    });

    document.body.addEventListener('click', function(e) {
        if (e.target.classList.contains('vsubmit')) {
            const email = document.querySelector('input[type=email]');
            const nick = document.querySelector('input[name=nick]');
            const reg = /^[A-Za-z0-9_-\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!email.value || !nick.value || !reg.test(email.value)) {
                const str = `<div class="valert txt-center"><div class="vtext">请填写正确的昵称和邮箱！</div></div>`;
                const vmark = document.querySelector('.vmark');
                vmark.innerHTML = str;
                vmark.style.display = 'block';

                e.stopPropagation();

                setTimeout(function() {
                    vmark.style.display = 'none';
                    vmark.innerHTML = '';
                }, 2500);
            }
        }
        }, true);
</script>



    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/8086094.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/13.jpg" class="responsive-img" alt="MyBatisPlus">
                        
                        <span class="card-title">MyBatisPlus</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/MyBatisPlus/" class="post-category">
                                    MyBatisPlus
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/MyBatisPlus/">
                        <span class="chip bg-color">MyBatisPlus</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/30bd1158.html">
                    <div class="card-image">
                        
                        <img src="/medias/banner/10.jpg" class="responsive-img" alt="04存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁+间隙锁">
                        
                        <span class="card-title">04存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁+间隙锁</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            存储过程和函数+游标+存储引擎+mysql体系+读写锁+行锁表锁++间隙锁
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-category">
                                    数据库
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">
                        <span class="chip bg-color">数据库</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Long<br />'
            + '文章作者: Long<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="1776127550"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2021</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Long</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">155.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "10";
                    var startDate = "25";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn/" target="_blank">闽ICP备xxxxxxx号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/vegetable-dog16546/" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1694162702@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1694162702" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1694162702" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="6788560391" class="tooltipped" target="_blank" data-tooltip="关注我的微博: 6788560391" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.11/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?aaa6c944b0ed07922901d7fc571a171d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

<!-- 深色模式按钮 -->
    <script>
        if (localStorage.getItem('dark') === '1') {
        document.body.classList.add('dark');
        }
        else if (new Date().getHours() >= 22 || new Date().getHours() < 7) {
        document.body.classList.add('dark');
        } 
        else if (matchMedia('(prefers-color-scheme: dark)').matches) {
        document.body.classList.add('dark');
        }
    </script>
    <a onclick="switchNightMode()" id="sma">
        <i class="fas fa-lightbulb" id="nightMode" aria-hidden="true"></i>
    </a>

    <!-- 天气接口控件   -->
    
        <script type="text/javascript">
        WIDGET = {FID: 'zLkJSQpqsh'}
        </script>
    <!-- <script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"></script> -->

    <script type="text/javascript">
      var windowWidth = $(window).width();
      if (windowWidth > 768) {
          document.write('<script type="text/javascript" src="https://apip.weatherdt.com/float/static/js/r.js?v=1111"><\/script>');
      }
    </script>
    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "4xxxxxxxe"
        });
        daovoice('update');
    </script>
    

	
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
